import books from '@/data/books.js'

const cart = {
  namespaced: true,
  state(){
    return {
      items: books
    }
  },
  mutations: {
    pushItemToCart(state, book){
      state.items.push(book)
    },
    deleteItem(state, id){
      let index = state.items.findIndex(item => item.id === id)
      if(index >= 0){
        state.items.splice(index, 1)
      }
    },
    incrementItemCount(state, {id, count}){
      let item = state.items.find(item => item.id === id)
      if(item){
        item.count += count
      }
    }
  },
  getters: {
    cartTotalPrice(state){
      return state.items.reduce((total, item) => {
        total += item.price * item.count
        return total
      }, 0)
    },
    cartItemPrice(state){
      return function(id){
        let item = state.items.find(item => item.id === id)
        if(item){
          return item.price * item.count
        }
      }
    }
  },
  actions: {
    addItemToCart(context, book){
      let item = context.state.items.find(item => item.id === book.id)
      if(item){
        context.commit('incrementItemCount', {id: book.id, count: book.count})
      }
      else {
        context.commit('pushItemToCart', book)
      }
    }
  }
}

export default cart